package com.wiloon.java8x.basic.encode;

import java.io.UnsupportedEncodingException;

public class Chinese {
    public static void main(String[] args) {
        String str = "中文0";
        System.out.println(str.length());
        System.out.println(str.getBytes().length);
        try {
            System.out.println(str.getBytes("UTF-8").length);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        try {
            System.out.println(getChineseLength(str, "UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public static int getChineseLength(String name, String endcoding)
            throws Exception {
        int len = 0;
        int j = 0;
        byte[] b_name = name.getBytes(endcoding);
        while (true) {
            short tmpst = (short) (b_name[j] & 0xF0);
            if (tmpst >= 0xB0) {
                if (tmpst < 0xC0) {
                    j += 2;
                    len += 2;
                } else if ((tmpst == 0xC0) || (tmpst == 0xD0)) {
                    j += 2;
                    len += 2;
                } else if (tmpst == 0xE0) {
                    j += 3;
                    len += 2;
                } else if (tmpst == 0xF0) {
                    short tmpst0 = (short) (((short) b_name[j]) & 0x0F);
                    if (tmpst0 == 0) {
                        j += 4;
                        len += 2;
                    } else if ((tmpst0 > 0) && (tmpst0 < 12)) {
                        j += 5;
                        len += 2;
                    } else if (tmpst0 > 11) {
                        j += 6;
                        len += 2;
                    }
                }
            } else {
                j += 1;
                len += 1;
            }
            if (j > b_name.length - 1) {
                break;
            }
        }
        return len;
    }
}
